

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="Blue~u~u~u">
  <meta name="author" content="Blue~u~u~u">
  <meta name="keywords" content="">
  <meta name="description" content="原型模式需求 现有一只羊，姓名为tom，年龄为1：颜色为白色，请编写程序创建和tom羊属性完全相同的10只羊  123456789101112&#x2F;&#x2F;传统方式public class Sheep &amp;#123;    private String name;    private int age;    private String color;    &#x2F;&#x2F;生成构造和getset方法以及toString">
<meta property="og:type" content="article">
<meta property="og:title" content="java-原型模式">
<meta property="og:url" content="http://www.slx.blue/2021/12/08/java-prototype/index.html">
<meta property="og:site_name" content="Blue~u~u~u~u">
<meta property="og:description" content="原型模式需求 现有一只羊，姓名为tom，年龄为1：颜色为白色，请编写程序创建和tom羊属性完全相同的10只羊  123456789101112&#x2F;&#x2F;传统方式public class Sheep &amp;#123;    private String name;    private int age;    private String color;    &#x2F;&#x2F;生成构造和getset方法以及toString">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-12-08T12:01:23.000Z">
<meta property="article:modified_time" content="2021-12-08T12:03:41.453Z">
<meta property="article:author" content="Blue~u~u~u">
<meta property="article:tag" content="设计模式">
<meta name="twitter:card" content="summary_large_image">
  
  <title>java-原型模式 - Blue~u~u~u~u</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"www.slx.blue","root":"/","version":"1.8.12","typing":{"enable":true,"typeSpeed":180,"cursorChar":"_","loop":true},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname"}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.0"></head>

<script src="https://cdn.jsdelivr.net/npm/jquery/dist/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome/css/font-awesome.min.css"/>
<script src="/live2d-widget/autoload.js"></script>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Blue~u~u</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/links/">
                <i class="iconfont icon-link-fill"></i>
                友链
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/images/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="java-原型模式">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2021-12-08 20:01" pubdate>
        2021年12月8日 晚上
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      4.6k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      14 分钟
    </span>
  

  
  
    
      <!-- 不蒜子统计文章PV -->
      <span id="busuanzi_container_page_pv" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="busuanzi_value_page_pv"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">java-原型模式</h1>
            
              <p class="note note-info">
                
                  本文最后更新于：6 个月前
                
              </p>
            
            <div class="markdown-body">
              <h3 id="原型模式"><a href="#原型模式" class="headerlink" title="原型模式"></a>原型模式</h3><h4 id="需求"><a href="#需求" class="headerlink" title="需求"></a>需求</h4><ul>
<li>现有一只羊，姓名为tom，年龄为1：颜色为白色，请编写程序创建和tom羊属性完全相同的10只羊</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//传统方式</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Sheep</span> </span>&#123;<br>    <span class="hljs-keyword">private</span> String name;<br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> age;<br>    <span class="hljs-keyword">private</span> String color;<br>    <span class="hljs-comment">//生成构造和getset方法以及toString等等...</span><br>&#125;<br> <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>     Sheep sheep = <span class="hljs-keyword">new</span> Sheep(<span class="hljs-string">&quot;tom&quot;</span>,<span class="hljs-number">1</span>,<span class="hljs-string">&quot;白色&quot;</span>);<br>     <span class="hljs-comment">//克隆十次...</span><br>     <span class="hljs-keyword">new</span> Sheep(sheep.getName(),sheep.getAge(),sheep.getColor());<br> &#125;<br></code></pre></td></tr></table></figure>

<p>传统方式的优缺点</p>
<ol>
<li>有点是比较好理解，简单易操作</li>
<li>在创建新的对象时，总是需要重新获取原始对象的属性，如果创建的对象比较复杂，效率较低</li>
<li>总是需要重新初始化对象，而不是动态的获得对象运行时的状态，不够灵活</li>
</ol>
<p>思路：<code>java</code>中Object类是所有类的父类，Object提供了一个clone方法，可以将一个<code>java</code>对象复制一份，但是需要实现clone的<code>java</code>类需要实现一个接口<code>Clonealbe</code>，该接口表示该类能够复制且具有复制的能力=&gt;原型模式</p>
<h4 id="基本介绍"><a href="#基本介绍" class="headerlink" title="基本介绍"></a>基本介绍</h4><ol>
<li>原型模式(Prototype模式)是指：用原型实例指定创建对象的种类，并且通过拷贝这些原型，创建新的对象</li>
<li>原型模式是一种创建型设计模式，允许一个对象在创建另外一个可定制的对象，无需知道如何创建的细节</li>
<li>工作的原理：通过将一个原型对象传给那个要发动创建的对象，这个要发动创建的对象通过请求原型对象拷贝他们来实施创建，即对象.clone() </li>
<li>形象理解：猴子拔出猴毛变成其他猴子</li>
</ol>
<p>改进：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Sheep</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Cloneable</span></span>&#123;<br>    <span class="hljs-keyword">private</span> String name;<br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> age;<br>    <span class="hljs-keyword">private</span> String color;<br>     <span class="hljs-comment">//生成构造和getset方法以及toString等等...</span><br>	<span class="hljs-comment">//克隆该实例 使用默认的clone方法来完成</span><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">protected</span> Object <span class="hljs-title">clone</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> CloneNotSupportedException </span>&#123;<br>        Sheep sheep = <span class="hljs-keyword">null</span>;<br>        Sheep clone = (Sheep) <span class="hljs-keyword">super</span>.clone();<br>        <span class="hljs-keyword">return</span> clone;<br>    &#125;<br>&#125;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Client</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span>  </span>&#123;<br>        Sheep sheep = <span class="hljs-keyword">new</span> Sheep(<span class="hljs-string">&quot;tom&quot;</span>,<span class="hljs-number">1</span>,<span class="hljs-string">&quot;包塞&quot;</span>);<br>        <span class="hljs-keyword">try</span> &#123;<br>            <span class="hljs-comment">//克隆十次</span><br>            Sheep clone1 = (Sheep) sheep.clone();<br>            Sheep clone2 = (Sheep) sheep.clone();<br>            <span class="hljs-comment">//....</span><br>        &#125; <span class="hljs-keyword">catch</span> (CloneNotSupportedException e) &#123;<br>            e.printStackTrace();<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<blockquote>
<p>原型模式在Spring框架中源码分析</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testImport</span><span class="hljs-params">()</span></span>&#123;<br> Object bean1 = applicationContext.getBean(xxx);     <br>    Object bean2 = applicationContext.getBean(xxx);  <br>    <span class="hljs-comment">//如果是scope = prototype 多例 就用到了原型模式</span><br>    <span class="hljs-comment">//getbean每次都是通过clone生成的对象 </span><br>&#125;<br></code></pre></td></tr></table></figure>

<p>原型模式完成对象的创建，如果被克隆的对象中有对象属性，那么克隆的时候并不会被克隆</p>
<h4 id="深拷贝和浅拷贝"><a href="#深拷贝和浅拷贝" class="headerlink" title="深拷贝和浅拷贝"></a>深拷贝和浅拷贝</h4><p>浅拷贝：</p>
<ol>
<li>对于数据类型是基本类型的成员变量，浅拷贝会直接进行值传递，也就是将该属性复制一份给新的对象</li>
<li>对于数据类型是应用数据类型的成员变量，比如成员变量是某个数组，某个类的对象等，那么浅拷贝会进行引用传递，也就是只将该成员变量的引用值(内存地址)复制一份给新的对象。实际上两个对象都指向同一个实例，所以这种情况下 一个对象中修改该成员变量会影响到另一个对象的该成员变量值</li>
<li>比如默认开启的对象克隆就是浅拷贝</li>
<li><code> Sheep clone2 = (Sheep) sheep.clone();</code></li>
</ol>
<p>深拷贝：</p>
<ol>
<li>复制对象的<strong>所有</strong>基本数据类型的成员变量值 </li>
<li>为所有应用数据类型的成员变量<strong>申请存储空间</strong>，并复制每个应用数据类型成员变量所引用的对象，直到该对象可达的所有对象，<strong>也就是说，对象进行深拷贝要对整个对象(包括引用对象)进行拷贝</strong></li>
<li>深拷贝实现方式1：<strong>重写clone</strong>方法来实现深拷贝</li>
<li>深拷贝实现方式2：通过<strong>序列化</strong>实现深拷贝  </li>
</ol>
<h4 id="小案例"><a href="#小案例" class="headerlink" title="小案例"></a>小案例</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//克隆引用对象</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DeepCloneTarget</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Serializable</span>,<span class="hljs-title">Cloneable</span> </span>&#123;<br><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> serialVersionUID = <span class="hljs-number">1L</span>;<br>    <span class="hljs-keyword">private</span> String cloneName;<br>    <span class="hljs-keyword">private</span> String cloneClass;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">DeepCloneTarget</span><span class="hljs-params">(String cloneName, String cloneClass)</span> </span>&#123;<br>        <span class="hljs-keyword">this</span>.cloneName = cloneName;<br>        <span class="hljs-keyword">this</span>.cloneClass = cloneClass;<br>    &#125;<br><br>    <span class="hljs-comment">//因为该类的属性都是string 所以直接用默认clone方式即可</span><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">protected</span> Object <span class="hljs-title">clone</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> CloneNotSupportedException </span>&#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">super</span>.clone();<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//要克隆的对象 实现了两种克隆方式</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DeepProtoType</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Serializable</span>,<span class="hljs-title">Cloneable</span> </span>&#123;<br><br>    <span class="hljs-keyword">public</span> String name;<span class="hljs-comment">//String 属性</span><br>    <span class="hljs-keyword">public</span> DeepCloneTarget deepCloneTarget;<span class="hljs-comment">//引用类型 //属性是对象 默认克隆会浅拷贝</span><br>    <span class="hljs-comment">//深拷贝-1 使用重写clone方法</span><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">protected</span> Object <span class="hljs-title">clone</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> CloneNotSupportedException </span>&#123;<br>        Object deep = <span class="hljs-keyword">null</span>;<br>        <span class="hljs-comment">//这里完成对基本数据类型(属性)和字符串的clone</span><br>        deep = <span class="hljs-keyword">super</span>.clone();<br>        <span class="hljs-comment">//对引用类型的属性进行单独处理</span><br>        DeepProtoType deepProtoType = (DeepProtoType) deep;<br>        deepProtoType.deepCloneTarget = (DeepCloneTarget) deepCloneTarget.clone();<br>        <span class="hljs-keyword">return</span> deepProtoType;<br>    &#125;<br><br>    <span class="hljs-comment">//深拷贝2 使用对象的序列化实现(推荐)</span><br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> Object <span class="hljs-title">deepClone</span><span class="hljs-params">()</span></span>&#123;<br><br>        <span class="hljs-comment">//创建流对象</span><br>        ByteArrayOutputStream bos = <span class="hljs-keyword">null</span>;<br>        ObjectOutputStream oos = <span class="hljs-keyword">null</span>;<br>        ByteArrayInputStream bis = <span class="hljs-keyword">null</span>;<br>        ObjectInputStream ois = <span class="hljs-keyword">null</span>;<br>        <span class="hljs-keyword">try</span> &#123;<br>            bos = <span class="hljs-keyword">new</span> ByteArrayOutputStream();<br>            oos = <span class="hljs-keyword">new</span> ObjectOutputStream(bos);<br>            oos.writeObject(<span class="hljs-keyword">this</span>); <span class="hljs-comment">//当前这个对象以对象流的方式输出 序列化</span><br>            <span class="hljs-comment">//再反序列化 读出来 相当于存了值 成功克隆了一个新的对象</span><br>            bis = <span class="hljs-keyword">new</span> ByteArrayInputStream(bos.toByteArray());<br>            ois = <span class="hljs-keyword">new</span> ObjectInputStream(bis);<br>            DeepProtoType copy = (DeepProtoType) ois.readObject();<br>            <span class="hljs-keyword">return</span> copy;<br>        &#125; <span class="hljs-keyword">catch</span> (Exception e) &#123;<br>            e.printStackTrace();<br>            <span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>;<br>        &#125;<span class="hljs-keyword">finally</span> &#123;<br>            <span class="hljs-keyword">try</span> &#123;<br>                bos.close();<br>                oos.close();<br>                bis.close();<br>                ois.close();<br>            &#125; <span class="hljs-keyword">catch</span> (IOException e) &#123;<br>                e.printStackTrace();<br>            &#125;<br>        &#125;<br>    &#125;<br>&#125;<br><br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//测试</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Client</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> CloneNotSupportedException </span>&#123;<br>        DeepProtoType dp = <span class="hljs-keyword">new</span> DeepProtoType();<br>        dp.name = <span class="hljs-string">&quot;小水牛&quot;</span>;<br>        dp.deepCloneTarget = <span class="hljs-keyword">new</span> DeepCloneTarget(<span class="hljs-string">&quot;大水牛&quot;</span>, <span class="hljs-string">&quot;敲能喝&quot;</span>);<br>        <span class="hljs-comment">//方式一 完成深拷贝</span><br>       <span class="hljs-comment">/*</span><br><span class="hljs-comment">        DeepProtoType clone = (DeepProtoType) dp.clone();</span><br><span class="hljs-comment">        System.out.println(dp.hashCode());//460141958</span><br><span class="hljs-comment">        System.out.println(clone.hashCode());//1163157884</span><br><span class="hljs-comment">       */</span><br>       <span class="hljs-comment">//方式二 完成深拷贝</span><br>        DeepProtoType p = (DeepProtoType) dp.deepClone();<br>        System.out.println(<span class="hljs-string">&quot;克隆原型：&quot;</span>+dp.name + <span class="hljs-string">&quot;--&quot;</span> + dp.deepCloneTarget.hashCode());<br>        <span class="hljs-comment">//克隆原型：小水牛--325040804</span><br><br>        System.out.println(<span class="hljs-string">&quot;克隆的对象&quot;</span>+p.name + <span class="hljs-string">&quot;--&quot;</span> + p.deepCloneTarget.hashCode());<br>        <span class="hljs-comment">//克隆的对象小水牛--2065951873</span><br>    &#125;<br>&#125;<br><span class="hljs-comment">//推荐使用的是通过序列化实现深拷贝，这样无论原型如何修改都不会影响克隆 因为直接通过流来反序列化创建</span><br></code></pre></td></tr></table></figure>

<h4 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h4><ol>
<li>创建新的对象比较复杂时，可以利用原型模式简化对象的创建过程，同时也能够提高效率</li>
<li>不用重新初始化对象，而是动态的获得对象运行时的状态</li>
<li>如果原型对象发生变化（增加或减少属性），其他克隆对象也会发生相应的变化，无需修改代码</li>
<li>在实现深克隆的时候 可能需要比较复杂的代码</li>
<li>缺点：需要为每一个类配备一个克隆方法，这对全新的类来说不是很难，但是对已有的类来说进行改造的时候 需要修改它的源代码，违背了<code>OCP</code>（开闭原则）。</li>
</ol>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/designMode/">designMode</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">设计模式</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客目前大部分文章都是参考尚硅谷或者马士兵教育的学习资料！<a href="http://www.atguigu.com/" rel="nofollow noopener"官网地址！</a> 
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2021/12/08/java-builder/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">java-构建者模式</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2021/12/08/java-observer/">
                        <span class="hidden-mobile">java-观察者模式</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
              <!-- Comments -->
              <article class="comments" id="comments" lazyload>
                
                  
                
                

              </article>
            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">

  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
	<!--《添加网站运行时间 -->
<br/>

<span id="timeDate">载入天数...</span><span id="times">载入时分秒...</span>
<script>
var now = new Date(); 

function createtime() {
    //此处修改你的建站时间或者网站上线时间
    var grt = new Date('11/02/2021 21:39:00');
    now.setTime(now.getTime() + 250);
    days = (now - grt) / 1000 / 60 / 60 / 24;

    dnum = Math.floor(days);
    hours = (now - grt) / 1000 / 60 / 60 - (24 * dnum);
    hnum = Math.floor(hours);
    if (String(hnum).length == 1) {
        hnum = "0" + hnum;
    }
    minutes = (now - grt) / 1000 / 60 - (24 * 60 * dnum) - (60 * hnum);
    mnum = Math.floor(minutes);
    if (String(mnum).length == 1) {
        mnum = "0" + mnum;
    }
    seconds = (now - grt) / 1000 - (24 * 60 * 60 * dnum) - (60 * 60 * hnum) - (60 * mnum);
    snum = Math.round(seconds);
    if (String(snum).length == 1) {
        snum = "0" + snum;
    }
    document.getElementById("timeDate").innerHTML = " 本站已各种夹缝中安全运行 " + dnum + " 天 ";
    document.getElementById("times").innerHTML = hnum + " 小时 " + mnum + " 分 " + snum + " 秒";
}
setInterval("createtime()", 250);
</script>

<!-- 添加网站运行时间》-->
  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
      typing(title)
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
